package io.github.liuyuhao412.manager.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@Component
@Order(1) // 优先执行
public class RequestLoggingFilter extends OncePerRequestFilter {

	private static final Logger log = LoggerFactory.getLogger(RequestLoggingFilter.class);

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		long start = System.currentTimeMillis();
		String method = request.getMethod();
		String url = request.getRequestURI();

		try {
			filterChain.doFilter(request, response); // 执行后续 Filter 和 Controller
		} finally {
			long duration = System.currentTimeMillis() - start;
			int status = response.getStatus();

			log.info("[REQUEST] method={} path={} status={} duration={}ms", method, url, status, duration);
		}
	}
}
